// history.js
const app = getApp();
const api = require('../../utils/api.js');

Page({
  data: {
    loading: false,
    historyRecords: [],
    noRecords: false,
    errorMessage: ''
  },
  
  onLoad() {
    this.loadHistory();
  },
  
  // 加载历史记录
  loadHistory() {
    const userInfo = app.globalData.userInfo || wx.getStorageSync('userInfo');
    
    if (!userInfo || !userInfo.userId) {
      this.setData({
        errorMessage: '请先登录',
        noRecords: true
      });
      return;
    }
    
    this.setData({ loading: true });
    
    wx.request({
      url: api.apiEndpoints.getDiagnosisHistoryUrl(),
      method: 'GET',
      data: {
        userId: userInfo.userId
      },
      success: (res) => {
        if (res.data.success) {
          const history = res.data.data || [];
          this.setData({
            historyRecords: history,
            noRecords: history.length === 0,
            loading: false
          });
        } else {
          this.setData({
            errorMessage: '获取历史记录失败: ' + (res.data.message || '未知错误'),
            loading: false,
            noRecords: true
          });
        }
      },
      fail: (err) => {
        this.setData({
          errorMessage: '网络请求失败: ' + err.errMsg,
          loading: false,
          noRecords: true
        });
      }
    });
  },
  
  // 查看历史记录详情
  viewDetail(e) {
    const index = e.currentTarget.dataset.index;
    const record = this.data.historyRecords[index];
    
    // 将记录存入全局变量，以便详情页使用
    app.globalData.currentRecordDetail = record;
    
    wx.navigateTo({
      url: '/pages/history/detail/detail'
    });
  },
  
  // 导航至诊断页面
  navigateToDiagnosis() {
    wx.switchTab({
      url: '/pages/diagnosis/diagnosis'
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadHistory();
    wx.stopPullDownRefresh();
  }
});
